package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.adapter.ReviewOrganizeAdapter;
import com.jp.knowledge.my.model.ColleagueAuditModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/4/14.
 */

public class ReviewOrganizeFragment extends Fragment implements CanRefreshLayout.OnRefreshListener, ResultSubscriber.OnResultListener, CanRefreshLayout.OnLoadMoreListener {

    private static final int REFRESH_CODE = 0x01;
    private static final int LOADMORE_CODE = 0x02;
    private static final int REVIEW_AGREE_CODE = 0x03;
    private static final int REVIEW_DISAGREE_CODE = 0x04;

    private String id;
    private int type;
    private int page;
    private List<ColleagueAuditModel> colleagueAuditModels;
    private ReviewOrganizeAdapter adapter;

    private Context mContext;
    private View contentView;
    private CanRefreshLayout canRefreshLayout;
    private RecyclerView recyclerView;
    private JpRefreshView footerView;

    private LoadingDialog loadingDialog;
    private SelectDialog selectDialog;
    private CommDialog disagreeDialog;

    public static ReviewOrganizeFragment newInstance(String id, int type){
        ReviewOrganizeFragment fragment = new ReviewOrganizeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(mContext == null) {
            mContext = getContext();
            Bundle bundle = getArguments();
            id = bundle.getString("id");
            type = bundle.getInt("type");
            page = 1;
            colleagueAuditModels = new ArrayList<>();

            contentView = View.inflate(mContext, R.layout.refresh_recycleview, null);
            canRefreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
            recyclerView = (RecyclerView) contentView.findViewById(R.id.can_content_view);
            footerView = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);

            canRefreshLayout.setOnRefreshListener(this);
            canRefreshLayout.setOnLoadMoreListener(this);

            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            recyclerView.setHasFixedSize(true);
            recyclerView.addItemDecoration(new JpDiver(mContext));

            adapter = new ReviewOrganizeAdapter(mContext, colleagueAuditModels);
            recyclerView.setAdapter(adapter);
            adapter.setReviewBtnClickListener(new ReviewOrganizeAdapter.ReviewBtnClickListener() {
                @Override
                public void onBtnClick(int position) {
                    selectDialog.setTag(position);
                    selectDialog.show();
                }
            });
            initDialog();
            canRefreshLayout.autoRefresh();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return contentView;
    }

    private void initDialog(){
        loadingDialog = new LoadingDialog(mContext);
        selectDialog = new SelectDialog(mContext);
        disagreeDialog = new CommDialog(mContext);

        selectDialog.setTag(0);
        selectDialog.addItem("同意");
        selectDialog.addItem("拒绝");
        selectDialog.visibleTitle(false);
        selectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
            @Override
            public void onSelectItemClick(int position) {
                int itemPosition = (int)selectDialog.getTag();
                if(position == 0){
                    reviewOrganize(itemPosition, true, null);
                } else{
                    disagreeDialog.setTag(itemPosition);
                    disagreeDialog.show();
                }
            }
        });

        disagreeDialog.setTag(0);
        disagreeDialog.setShowWithKeyword(true);
        disagreeDialog.setEditHint("请输入拒绝理由");
        disagreeDialog.setRight("拒绝");
        disagreeDialog.setRightClickDismiss(false);
        disagreeDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) disagreeDialog.getTag();
                String disagreeReason = disagreeDialog.getEditText();
                if(disagreeReason.trim().length() == 0) {
                    ToasUtil.toast(mContext, "请输入合理的拒绝理由");
                } else {
                    reviewOrganize(position, false, disagreeDialog.getEditText());
                    disagreeDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData(page);
    }

    @Override
    public void onLoadMore() {
        if(footerView.isLoadComplete())
            canRefreshLayout.loadMoreComplete();
        else
            getData(++page);
    }

    private void getData(int page){
        JsonObject param = new JsonObject();
        param.addProperty("id", id);
        param.addProperty("type", type);
        param.addProperty("page", page);
        HttpHelper.getInstance(mContext).getAuditList(param, page==1 ? REFRESH_CODE : LOADMORE_CODE, this);
    }

    private void reviewOrganize(int position, boolean isAgree, String reason){
        loadingDialog.show();
        ColleagueAuditModel colleagueAuditModel = colleagueAuditModels.get(position);
        JsonObject param = new JsonObject();
        param.addProperty("userId", colleagueAuditModel.getUserId());
        param.addProperty("organizeId", id);
        param.addProperty("organizeType", type);
        param.addProperty("action", isAgree?1:2);
        if(!isAgree)
            param.addProperty("reason", reason);
        if(isAgree)
            HttpHelper.getInstance(mContext).commitAudit(param, position*10+REVIEW_AGREE_CODE, this);
        else
            HttpHelper.getInstance(mContext).commitAudit(param, position*10+REVIEW_DISAGREE_CODE, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_CODE) {
            canRefreshLayout.refreshComplete();
        } else if(requestType == LOADMORE_CODE) {
            canRefreshLayout.loadMoreComplete();
        } else if(requestType%10 == REVIEW_AGREE_CODE || requestType%10 == REVIEW_DISAGREE_CODE){
            loadingDialog.cancel();
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_CODE || requestType == LOADMORE_CODE){
            if(requestType == REFRESH_CODE) {
                colleagueAuditModels.clear();
                footerView.setLoadComplete(false);
            }
            List<ColleagueAuditModel> colleagueAuditModelList = data.getList(ColleagueAuditModel.class);
            if(colleagueAuditModelList != null && colleagueAuditModelList.size() > 0)
                for(ColleagueAuditModel colleagueAuditModel : colleagueAuditModelList)
                    if(colleagueAuditModel.getStatus() != 1)            // 不显示已同意的
                        colleagueAuditModels.add(colleagueAuditModel);
            adapter.updateAdapter(colleagueAuditModels);
            if(adapter.getItemCount() == 0 && dataEmptyListener != null)
                dataEmptyListener.dataIsEmpty(this);
            if(requestType == LOADMORE_CODE && (colleagueAuditModelList == null || colleagueAuditModelList.size() == 0))
                footerView.setLoadComplete(true);
        } else if(requestType%10 == REVIEW_AGREE_CODE){
            int position = requestType/10;
            adapter.removeData(position);
            if(adapter.getItemCount() == 0 && dataEmptyListener != null)
                dataEmptyListener.dataIsEmpty(this);
        } else if(requestType%10 == REVIEW_DISAGREE_CODE){
            int position = requestType/10;
            ColleagueAuditModel colleagueAuditModel = colleagueAuditModels.get(position);
            colleagueAuditModel.setAuditState(2);
            adapter.notifyItemChanged(position);
        }
    }

    private DataEmptyListener dataEmptyListener;
    public void setDataEmptyListener(DataEmptyListener listener){
        this.dataEmptyListener = listener;
    }
    public interface DataEmptyListener{
        void dataIsEmpty(ReviewOrganizeFragment fragment);
    }
}
